package cn.wx.fileclient.ui;

import cn.wx.fileclient.config.Environment;
import cn.wx.fileclient.service.FileRecognition;
import cn.wx.fileclient.service.FileScan;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 文件扫描主操作
 * Created by IntelliJ IDEA.
 * cn.wx.fileclient.ui
 * name：Operator
 * user：pengpeng
 * date:2020/11/2
 * time:14:19
 */
public class Operator implements FileClientWindow {

    private Stage stage;
    private FileClientWindow parent;
    private FileClientWindow answerDate;
    private FileClientWindow accountDate;
    private Label fileAbsPath;
    private String scanDirection;
    private List<String> fileList = new ArrayList<>();
    Label fileTotalCount;
    //当前任务提醒
    Label currentTask;
    Label currentTaskInfo;
    Label accountDownCount;

    //扫描按钮
    private Button scanButton;
    //开始按钮
    private Button start;

    public Operator(FileClientWindow parent) throws FileNotFoundException {
        this.parent = parent;
        Environment.init();
        this.parent = parent;
        this.stage = new Stage();
//        answerDate=new DateSelector(this,"answer");
//        accountDate=new DateSelector(this,"account");
        start();
        this.stage.getIcons().add(new Image(Login.class.getResourceAsStream("/images/icon.png")));
        if (Environment.spider == null) {
            return;
        }
        System.out.println("destroy old spider");
        Environment.spider.destroy();
        Environment.spider = null;
    }

    //初始化界面
    private void initInterface() {
        this.scanButton = new Button("设置扫描文件路径");
        this.start = new Button("开始扫描");
        ProgressIndicator accountStage = new ProgressIndicator(0);
        ProgressIndicator answerStage = new ProgressIndicator(0);
        currentTask = new Label("任务进程");
        currentTaskInfo = new Label("请选择文件");
        Label answerDownTotal = new Label("文件总数：");
        fileTotalCount = new Label("0");
        Label accountDown = new Label("已解析资料数：");
        accountDownCount = new Label("0");
        Label accountDownTotal = new Label("失败数：");
        Label accountDownTotalCount = new Label("0");
        this.fileAbsPath = new Label("");
        Label pop = new Label("");
        pop.setTextFill(Color.web("#FF0000"));
        pop.setFont(new Font("Arial", 30));
        //网格布局
        GridPane gridPane = new GridPane();
        //设置网格位置
//        gridPane.add(account, 0,0,2,1);
//        gridPane.add(answer, 0,1,2,1);
        gridPane.add(this.scanButton, 0, 2, 2, 1);
        gridPane.add(this.start, 0, 3, 2, 1);
//        gridPane.add(accountStage, 0, 4);
//        gridPane.add(answerStage, 1, 4);
        gridPane.add(currentTask, 0, 5);
        gridPane.add(currentTaskInfo, 1, 5);
        gridPane.add(answerDownTotal, 0, 6);
        gridPane.add(fileTotalCount, 1, 6);

        gridPane.add(accountDown, 0, 7);
        gridPane.add(accountDownCount, 1, 7);
        gridPane.add(accountDownTotal, 0, 8);
        gridPane.add(accountDownTotalCount, 1, 8);
        gridPane.add(fileAbsPath, 0, 9);
        gridPane.add(pop, 0, 10);

        GridPane.setHalignment(accountStage, HPos.CENTER);
        GridPane.setHalignment(answerStage, HPos.CENTER);
        GridPane.setMargin(accountStage, new Insets(0, 100, 0, 0));
        //设置单独组件的上下左右的间距
        // GridPane.setMargin(login, new Insets(0,0,0,115));
        gridPane.setAlignment(Pos.CENTER);
        //设置垂直间距
        gridPane.setVgap(20);
        //设置水平间距
        gridPane.setHgap(5);

        Scene scene = new Scene(gridPane);
        scene.getStylesheets().add(
                getClass().getResource("/ui/OperatorStyle.css")
                        .toExternalForm());
        stage.setScene(scene);
        stage.setTitle("用户资料回文下载器");
        stage.setHeight(800);
        stage.setWidth(650);
    }

    @Override
    public void start() throws FileNotFoundException {
        initInterface();
        setScanPathActoin();
        // 开始下载被点击
        setStartActoin();
        stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                Environment.alive = false;
                if (Environment.spider == null) {
                    return;
                }
                System.out.println("destroy old spider");
                Environment.spider.destroy();
                Environment.spider = null;
                if (parent != null) {
                    parent.show();
                }
            }
        });

    }

    //设置扫描路径开始事件
    private void setScanPathActoin() {
        this.scanButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                DirectoryChooser fileChooser = new DirectoryChooser();
                fileChooser.setTitle("选择保存路径");
                File file = fileChooser.showDialog(stage);
                if (file != null && file.isDirectory()) {
                    scanDirection = file.getPath();
                    if (!StringUtils.isEmpty(scanDirection) && scanDirection.length() > 10)
                        fileAbsPath.setText(scanDirection.substring(0, 15) + ".....");
                    else
                        fileAbsPath.setText(file.getPath());
//                    Environment.answerFilePath = Paths.get(file.getPath(), "发文").toString();
//                    Environment.accountFilePath = Paths.get(file.getPath(), "用户资料").toString();
                }
            }
        });

    }

    //点击开始扫描按钮事件
    private void setStartActoin() {
        this.start.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                initShowParam();
                System.out.println("开始扫描文件:" + fileAbsPath.getText());
                //扫描文件
                currentTaskInfo.setText("文件扫描开始");
                File scanFile = new File(scanDirection);
                //构建成功文件夹与失败文件夹
                boolean signBuildSuccessAndFailDir = buildSuccessAndFailDir(scanDirection);
                if (signBuildSuccessAndFailDir) {

                    //todo 直接扫描识别
                    FutureTask<List<String>> task = new FutureTask<>(new FileScan(scanDirection));
                    Thread scanThread = new Thread(task, "fileScan");
                    scanThread.start();
                    try {
                        //获取扫描结果
                        List<String> filesList = task.get();
                        List<String> fail = fileRecognit(filesList);
                        if (!CollectionUtils.isEmpty(fail)){
                            Integer fail_count = fail.size();
                            fileTotalCount.setText(""+fail_count);
                            Integer success_count = (filesList.size()-fail.size());
                            System.out.println(fail_count);
                            System.out.println(success_count);
                            accountDownCount.setText(""+success_count);
                            alert("提示!!", "操作结果", "成功数："+success_count+" ，  失败数"+fail_count+"    ,请前往文件查看！失败文件夹：fail_Dir");
                        }else {
                            alert("提示", "文件成功文件数：", ""+filesList.size());
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                } else {
                    //todo 失败了
                }


            }

            private void initShowParam() {
                currentTaskInfo.setText("文件正在扫描");
            }
        });
    }

    //构建成功与失败文件夹
    private boolean buildSuccessAndFailDir(String scanDirection) {
        File scanfile = new File(scanDirection);
        if (scanfile.isFile()) {
            return false;
        }
        String success_Dir = scanDirection + "\\success_Dir";
        String fail_Dir = scanDirection + "\\fail_Dir";

        File successDirFile = new File(success_Dir);
        if (!successDirFile.exists())
            successDirFile.mkdirs();

        File failDirFile = new File(fail_Dir);
        if (!failDirFile.exists())
            failDirFile.mkdirs();
        return true;
    }

    private List<String> fileRecognit(List<String> filesList) throws ExecutionException, InterruptedException {
        String success_Dir = scanDirection + "\\success_Dir";
        String fail_Dir = scanDirection + "\\fail_Dir";
        System.out.println("成功目录："+success_Dir);
        System.out.println("失败目录："+fail_Dir);
        if (!CollectionUtils.isEmpty(filesList)) {
            System.out.println("文件总数：" + filesList.size());
            fileTotalCount.setText("" + filesList.size());
            // 文件识别
            currentTaskInfo.setText("正在文件识别");
            FutureTask<List<String>> task1 = new FutureTask<>(new FileRecognition(success_Dir,fail_Dir,filesList, scanDirection));
            new Thread(task1).start();
            // 失败文件数
            List<String> failCount = task1.get();
            if (!CollectionUtils.isEmpty(failCount)) {
                System.out.println("扫描失败文件数:" + failCount.size());
                return failCount;
                //todo 文件移植
            }
        } else {
            alert("提示", "文件夹为空", "请确认文件夹设置是否正确");
        }
        return null;
    }

    private void alert(String title, String subject, String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(subject);
        alert.setContentText(content);
        alert.showAndWait();
    }


    @Override
    public void show() {
        stage.show();
    }

    @Override
    public void hide() {
        stage.hide();
    }
}
